package com.sskj.wallet.ui.activity;


import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.LazyLoaders;
import com.github.yoojia.inputs.StaticScheme;
import com.github.yoojia.inputs.ValueScheme;
import com.github.yoojia.inputs.WidgetAccess;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.CoinEnum;
import com.sskj.lib.bean.ScanBean;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.WalletBean;
import com.sskj.lib.model.room.WalletBeanViewModel;
import com.sskj.lib.util.SchemeUtil;
import com.sskj.wallet.R;
import com.sskj.wallet.R2;
import com.sskj.wallet.bean.CreateBean;
import com.sskj.wallet.component.DaggerUserDataComponent;
import com.sskj.wallet.presenter.ImportWalletActivityPresenter;

import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

@Route(path = RConfig.WALLET_IMPORT_WALLET)//导入钱包
public class ImportWalletActivity extends BaseActivity<ImportWalletActivityPresenter> {
    @BindView(R2.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R2.id.tvWordTitle)
    TextView tvWordTitle;
    @BindView(R2.id.etWord)
    EditText etWord;
    @BindView(R2.id.llPath)
    LinearLayout llPath;
    @BindView(R2.id.etName)
    EditText etName;
    @BindView(R2.id.etPwd)
    EditText etPwd;
    @BindView(R2.id.ivPwdToggle)
    ImageView ivPwdToggle;
    @BindView(R2.id.etPwdAgain)
    EditText etPwdAgain;
    @BindView(R2.id.ivPwdToggleAgain)
    ImageView ivPwdToggleAgain;
    @BindView(R2.id.checkbox)
    CheckBox checkbox;
    @BindView(R2.id.tvAgreement)
    TextView tvAgreement;
    @BindView(R2.id.btSubmit)
    Button btSubmit;
    @Autowired
    CoinEnum coinEnum;
    private int currentPos = 0;
    private AndroidNextInputs inputs;
    private boolean isSeeAgain;
    private boolean isSee;
    @Inject
    WalletBeanViewModel walletBeanViewModel;
    @Autowired
    boolean isFirst = true;

    @Override
    protected int getLayoutId() {
        return R.layout.wallet_activity_import_wallet;
    }

    @Override
    public ImportWalletActivityPresenter getPresenter() {
        return new ImportWalletActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        if (coinEnum == CoinEnum.BTC) {
            setTitle(App.INSTANCE.getString(R.string.wallet_importWalletActivity1_j));
        } else {
            setTitle(App.INSTANCE.getString(R.string.wallet_importWalletActivity2_j));
        }
        setRightImage(R.mipmap.wallet_icon_scan, v -> {

            ARouter.getInstance().build(RConfig.LIB_SCAN).navigation();
        });
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.wallet_importWalletActivity3_j), 0, 0));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.wallet_importWalletActivity4_j), 0, 0));
        if (coinEnum == CoinEnum.ETH) {
            tabItems.add(new TabItem("Keystore", 0, 0));
        }
        commonTabLayout.setTabData(tabItems);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (position) {
                    case 0:
                        changePrivateKey();
                        break;
                    case 1:
                        changeHelpWord();
                        break;
                    case 2:
                        changeKeyStore();
                        break;
                }
                currentPos = position;
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        inputs = new AndroidNextInputs();
        WidgetAccess widgetAccess = new WidgetAccess(this);
        LazyLoaders lazyLoaders = new LazyLoaders(this);
        inputs.clear();
        inputs
                .add(widgetAccess.findEditText(R.id.etWord), StaticScheme.required())
                .add(widgetAccess.findEditText(R.id.etName), StaticScheme.required())
                .add(widgetAccess.findEditText(R.id.etPwd), StaticScheme.required(), SchemeUtil.getPwdScheme())
                .add(widgetAccess.findEditText(R.id.etPwdAgain), ValueScheme.equalsTo(lazyLoaders.fromEditText(R.id.etPwd)))
        ;
    }

    private void changeKeyStore() {
        etWord.setText("");
        tvWordTitle.setText("Keystore");
        etWord.setHint(App.INSTANCE.getString(R.string.wallet_importWalletActivity5_j));
        llPath.setVisibility(View.GONE);
    }

    private void changeHelpWord() {
        etWord.setText("");
        tvWordTitle.setText(App.INSTANCE.getString(R.string.wallet_importWalletActivity6_j));
        etWord.setHint(App.INSTANCE.getString(R.string.wallet_importWalletActivity7_j));
        llPath.setVisibility(View.VISIBLE);

    }

    private void changePrivateKey() {
        etWord.setText("");
        tvWordTitle.setText(App.INSTANCE.getString(R.string.wallet_importWalletActivity3_j));
        etWord.setHint(App.INSTANCE.getString(R.string.wallet_importWalletActivity8_j));
        llPath.setVisibility(View.GONE);

    }

    @Override
    protected void initEvent() {
        ClickUtil.click(200, ivPwdToggleAgain, () -> {
            isSeeAgain = !isSeeAgain;
            etPwdAgain.setTransformationMethod(isSeeAgain ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
            ivPwdToggleAgain.setImageResource(isSeeAgain ? R.mipmap.lib_icon_show : R.mipmap.lib_icon_hide);
        });
        ClickUtil.click(200, ivPwdToggle, () -> {
            isSee = !isSee;
            etPwd.setTransformationMethod(isSee ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
            ivPwdToggle.setImageResource(isSee ? R.mipmap.lib_icon_show : R.mipmap.lib_icon_hide);

        });
        ClickUtil.click(tvAgreement, () -> {

            ARouter.getInstance().build(RConfig.MINE_NEWS_DETAIL).withString(Constans.WALLET_XIEYI, "reg_agree").navigation();

        });
        ClickUtil.click(btSubmit, () -> {
            if (inputs.test()) {
                if (!checkbox.isChecked()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.wallet_createWalletActivity2_j));
                    return;
                }
                int action = -1;
                switch (currentPos) {
                    case 0:
                        action = 3;
                        break;
                    case 1:
                        action = 2;
                        break;
                    case 2:
                        action = 4;
                        break;
                }
                mPresenter.createAccount(isFirst, coinEnum.getId() + "", action + "", etWord.getText().toString(), etPwd.getText().toString(), "m/44'/60'/0'/0/0");
            }
        });
    }


    public void createSuccess(CreateBean data) {

        if (coinEnum == CoinEnum.ETH || isFirst) {
            WalletBean walletBean = new WalletBean(data.getEth().getAddr(), data.getEth().getPri(), CoinEnum.ETH.getCode(), CoinEnum.ETH.getId(), etName.getText().toString(), etPwd.getText().toString());
            walletBean.setKeystore(data.getEth().getKsJson());
            walletBean.setWords(data.getEth().getMnemonic());
            walletBean.setBackup(!(coinEnum!=CoinEnum.ETH&&isFirst));
            walletBeanViewModel.insert(walletBean);

        }
        if (coinEnum == CoinEnum.BTC || isFirst) {
            WalletBean walletBean = new WalletBean(data.getBtc().getAddr(), data.getBtc().getPri(), CoinEnum.BTC.getCode(), CoinEnum.BTC.getId(), etName.getText().toString(), etPwd.getText().toString());
            walletBean.setWords(data.getEth().getMnemonic());
            walletBean.setBackup(!(coinEnum!=CoinEnum.BTC&&isFirst));
            walletBeanViewModel.insert(walletBean);
        }

        ARouter.getInstance().build(RConfig.WALLET_CREATE_WALLET_SUCCESS).withBoolean(Constans.IS_IMPORT, true).navigation();
        finish();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void scanBack(ScanBean scanBean){
        etWord.setText(scanBean.getContent());
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
